package at.fhj.itm10.ticketmaster.dao;

/**
 * 
 * @author Gerald Hambrosch
 *
 */

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import at.fhj.itm10.ticketmaster.entities.Entity;
import at.fhj.itm10.ticketmaster.entities.EventType;

public class EventTypeDAO extends AbstractDAO {

	private static final String PRIMARYKEY_NAME = "id";
	

	private static final String SQL_INSERT ="INSERT INTO `eventtype`(`text`)"+
			"VALUES(?)";
	
	private static final String SQL_UPDATE = "UPDATE `eventtype` SET `text` = ?  WHERE `id` = ?";
	
	private static final String SQL_DELETE = "DELETE FROM `eventtype` WHERE `id` = ?";
	
	private static final String SQL_FINDBYID = "SELECT * FROM `eventtype` WHERE `id` = ?";
	
	private static final String SQL_FINDALL = "SELECT * FROM `eventtype`";

	
	public EventTypeDAO(Connection connection) throws DAOException {
		super(connection);
	}
	
	public void insert(EventType entity) throws DAOException {
		checkForValidEntity(entity);
		PreparedStatement statement = prepareStatement(SQL_INSERT);

		try {
			statement.setString(1,entity.getText());
		} catch (SQLException e) {
			throw new DAOException(e);
		}
		
		super.processInsert(statement, entity);
	}

	public void update(EventType entity) throws DAOException {
		checkForValidEntity(entity);
		PreparedStatement statement = prepareStatement(SQL_UPDATE);
		
		try {

			statement.setString(1,entity.getText());
			statement.setLong(2, entity.getId());
		} catch (SQLException e) {
			throw new DAOException(e);
		}
		
		super.processUpdate(statement, entity);
	}

	public void delete(EventType eventtype1) throws DAOException {
		checkForValidEntity(eventtype1);

		super.doDelete(prepareStatement(SQL_DELETE), eventtype1);
	}

	public EventType findById(long id) throws DAOException {
		EventType entity = (EventType) retrieveEntity(id);
		if (entity != null) {
			return entity;
		}

		return (EventType) super.doFindOne(id, prepareStatement(SQL_FINDBYID));
	}

	public List<EventType> findAll() throws DAOException {
		return super.doFindMore(PRIMARYKEY_NAME, prepareStatement(SQL_FINDALL));
	}
	
	@Override
	protected Entity fillEntityByResult(ResultSet resultSet) throws DAOException {
		EventType eventtype = new EventType();
		
		try {
			eventtype.setId(resultSet.getLong(PRIMARYKEY_NAME));
			eventtype.setText(resultSet.getString("text"));
		} catch (SQLException e) {
			throw new DAOException(e);
		}

		return eventtype;
	}
}